package com.andnnl.ratelimit;

import com.andnnl.future.ThreadUtil;
import com.google.common.util.concurrent.RateLimiter;

import java.util.HashMap;
import java.util.Map;

/**
 * 做接口访问限制，访问一次获取一批数据，如果每个用户访问有数据，每秒最多访问10次，如果没数据，直接返回空，1秒最多访问1次，接口支持多用户同时访问的，每个用户需要自己的RateLimiter
 * Created by chenss on 2024/3/18.
 */
public class SdkAccessLimitTest {

        private static final Map<String, RateLimiter> rateLimitersWithData = new HashMap<>();
        private static final Map<String, RateLimiter> rateLimitersWithoutData = new HashMap<>();

        public static void main(String[] args) {
            // 模拟用户访问接口
            for (int i = 0; i < 20; i++) {
                String userId = "user" + i % 2;
                boolean hasData = i % 2 == 0; // 模拟数据是否存在

                RateLimiter limiter;
                if (hasData) {
                    limiter = rateLimitersWithData.computeIfAbsent(userId, k -> RateLimiter.create(5));
                } else {
                    limiter = rateLimitersWithoutData.computeIfAbsent(userId, k -> RateLimiter.create(1));
                }

                if (limiter.tryAcquire()) {
                    System.out.println(System.currentTimeMillis()+" "+userId + " accessed the API " + hasData);
                } else {
                    System.out.println(System.currentTimeMillis()+" "+userId + " failed to access the API "+ hasData);
                }
                ThreadUtil.sleep(200);
            }
        }
    }
